25. Exercise: Foreground vs. Background
L1 A25 Handling Messages In Foreground Vs Background
Exercise
You want to make sure the user sees a notification popping up as a reminder so let’s implement some code to trigger a notification.
- To do that, open the
onMessageReceived()function inMyFirebaseMessagingServiceagain. Right after the code you recently added to check the data message, you will add code which sends a notification using the notifications framework.
// MyFirebaseMessagingService.kt
// TODO: Step 3.6 check messages for notification and call sendNotification
// Check if message contains a notification payload.
remoteMessage?.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
sendNotification(it.body!!)
}
- Check notification property and the
remoteObjectis notnulland call thesendNotificationfunction.sendNotificationfunctions gets an instance ofNotificationManagerand calls thesendNotificationextension function you previously wrote.
- If you run the app again and send a notification by using Notifications composer, you should see a notification regardless of if the app is in foreground or background.